package com.bruce.springcloud.eureka.consumer.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.bruce.springcloud.common.CommonResult;
import com.bruce.springcloud.common.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    private static final String PAYMENT_SERVICE_URL = "http://CLOUD-PROVIDE-PAYMENT" ;

    @Resource
    private RestTemplate restTemplate ;


    @Resource
    private DiscoveryClient discoveryClient ;

    @PostMapping("/createPayment")
    public CommonResult<Payment> createPayment(@RequestBody Payment payment){
        CommonResult<Payment> result  = new CommonResult<>() ;
        if(payment == null){
            result.setCode(200);
            result.setMessage("请输入payment数据");
            return result ;
        }
        return  restTemplate.postForObject(PAYMENT_SERVICE_URL + "/payment/create",payment,CommonResult.class) ;
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        log.info("get payment id :" + id);
        CommonResult<Payment> result = new CommonResult<>() ;
        List<ServiceInstance> serviceInstances =  discoveryClient.getInstances("CLOUD-PROVIDE-PAYMENT") ;
        if(CollectionUtil.isEmpty(serviceInstances)){
            result.setCode(200);
            result.setMessage("获取不到payment服务");
            return result ;
        }
        result = restTemplate.getForObject(PAYMENT_SERVICE_URL + "/payment/findById/" + id, CommonResult.class);
        return result ;
    }
}
